package com.sec.android.app.myfiles.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.Formatter;
import android.util.LruCache;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.samsung.android.sdk.slinkcloud.CloudGatewayDeviceInfoUtils;
import com.samsung.android.sdk.slinkcloud.CloudGatewayMediaStore;
import com.samsung.android.sdk.slinkcloud.CloudGatewaySignInUtils;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.AbsMyFilesActivity;
import com.sec.android.app.myfiles.activity.CloudUsageActivity;
import com.sec.android.app.myfiles.dialog.UnableToAccessServerDialogFragment;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.feature.MultiWindowMgr;
import com.sec.android.app.myfiles.feature.PrivateModeMgr;
import com.sec.android.app.myfiles.feature.layout.AbsLayoutImp;
import com.sec.android.app.myfiles.feature.layout.split.TabletLayoutImp;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.fragment.filelist.FileListActionMenu;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.info.FileType;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.module.local.category.CategoryFileRecord;
import com.sec.android.app.myfiles.module.local.recent.RecentFileRecord;
import com.sec.android.app.myfiles.module.optimizestorage.OptimizeStorageFileRecord;
import com.sec.android.app.myfiles.module.search.SearchFileRecord;
import com.sec.android.app.myfiles.module.trash.TrashFileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.util.securefolder.SecureConstants;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

public class UiUtils {
    private static final String TAG = "UiUtils";
    private static final Pattern PATTERN_SAMSUNG_TALKBACK = Pattern.compile(
            ".*com.samsung.android.app.talkback.TalkBackService.*", Pattern.CASE_INSENSITIVE);
    private static final Pattern PATTERN_GOOGLE_TALKBACK = Pattern.compile(
            ".*com.google.android.marvin.talkback.TalkBackService.*", Pattern.CASE_INSENSITIVE);
    private static final Pattern PATTERN_YEARLESS_DATE = Pattern.compile("[^DdMm]*[Yy]+[^DdMm]*");
    private static final Pattern PATTERN_YEARLESS_DATE_FOR_PT_BR = Pattern.compile("[^DdMm]*[de]*[^DdMm]*[de]*[Yy]+");
    private static final Pattern PATTERN_YEARLESS_DATE_FOR_LV = Pattern.compile("[^Dd.Mm]*");
    private static final int PLURAL_QUANTITY_OTHER = 9999; // make sure that it will get other quantity in plural strings with quantity id # 1.

    private static final float PARTIAL_VIEW_WEIGHT = 0.75f;
    private static final float FULL_VIEW_WEIGHT = 1.0f;

    public static boolean isTalkBackEnabled(Context context) {
        boolean talkBackEnabled = false;
        String accessibilityService = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (accessibilityService != null) {
            talkBackEnabled = PATTERN_SAMSUNG_TALKBACK.matcher(accessibilityService).matches() ||
                    PATTERN_GOOGLE_TALKBACK.matcher(accessibilityService).matches();
        }
        return talkBackEnabled;
    }

    public static boolean isEasyMode(Context context) {
        if (context == null) {
            return false;
        }
        boolean isEasyModeSetting = (Settings.System.getInt(context.getContentResolver(), "easy_mode_switch", 1) == 0);
        Log.d(context, "EasyModeSetting is : " + String.valueOf(isEasyModeSetting));
        return isEasyModeSetting;
    }

    // If my caller is AndroidForWork(BYOD), it returns true.
    public static boolean isAfwForBYOD(Context context) {
        //TODO HYL  getUserCount need MANAGE_USERS Permission, it seems that this permission pretectionlevel is signature|system
        return false;
    }

    // If my caller is AndroidForWork(CL), it returns true.
    private static boolean isAfwForCL(Context context) {
        DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        if (dpm != null) {
            List<ComponentName> components = dpm.getActiveAdmins();
            if (components != null) {
                for (ComponentName name : components) {
                    if (dpm.isDeviceOwnerApp(name.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isAndroidForWorkMode(Context context) {
        return (AppFeatures.isBYOD() || isAfwForCL(context));
    }

    public static boolean isUPSM(Context context) {
        return false;
    }

    public static boolean isFactoryMode(Context context) {
        boolean isFactoryMode = false;

        // Remove the code which we don't use in Factory Mode on 2015.09.15
        // TelephonyManager mTelephonyManager = (TelephonyManager)
        // context.getSystemService(Context.TELEPHONY_SERVICE);

        // Case #1 - Check SHOULD_SHUT_DOWN value. If the value is 1, then it's
        // factory mode.
        try {
            if (Settings.System.getInt(context.getContentResolver(), "SHOULD_SHUT_DOWN", 0) == 1) {
                Log.d(TAG, "Factory mode is enabled by Case #1");
                isFactoryMode = true;
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception:" + e.toString());
        }

        // Remove the code which we don't use in Factory Mode on 2015.09.15
        // Case #2 - Check IMSI value. If the value is 999999999999999, then
        // it's factory mode.
        /*
        if (isFactoryMode == false) {
            if ("999999999999999".equals(mTelephonyManager.getSubscriberId())) {
                Log.d(this, "Factory mode is enabled by Case #2");
                isFactoryMode = true;
            }
        }
        */

        // Case #3 - Check /efs/FactoryApp/factorymode. If the value is OFF,
        // then it's factory mode.
        if (!isFactoryMode) {
            if (AppFeatures.IS_FACTORY_MODE) {
                Log.d(TAG, "Factory mode is enabled by Case #3");
                isFactoryMode = true;
            } else {
                Log.d(TAG, "Not factory mode");
            }
        }

        return isFactoryMode;
    }

    private static boolean uriHasUserId(Uri uri) {
        return uri != null && !TextUtils.isEmpty(uri.getUserInfo());
    }

    public static Uri addUserIdToUri(Uri uri) {
        if (uri == null)
            return null;

        int userId = SemFwWrapper.semGetMyUserId();

        //TODO HYL USERID
        if (/*userId != UserHandle.SEM_USER_CURRENT && */ ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            if (!uriHasUserId(uri)) {
                // We don't add the user Id if there's already one
                Uri.Builder builder = uri.buildUpon();
                builder.encodedAuthority(userId + "@" + uri.getEncodedAuthority());
                return builder.build();
            }
        }
        return uri;
    }

    public static boolean needCheckableCheck(NavigationInfo naviInfo, FileRecord record, boolean isShareMode) {
        boolean bRet = false;
        if (isShareMode) {
            return true;
        }
        if (naviInfo != null) {
            AbsMyFilesFragment curFragment = naviInfo.getCurFragment();
            if (naviInfo.isPickerMode()) {
                bRet = true;
            } else if (curFragment != null) {
                if ((record.getStorageType() == StorageType.Trash) && curFragment.isSelectActionMode()) {
                    bRet = true;
                }
            }
        }
        return bRet;
    }

    public static boolean isCheckable(Context context, FileRecord record, NavigationInfo naviInfo, boolean isShareMode) {
        boolean bRet = false;
        if (record != null) {
            if (needCheckableCheck(naviInfo, record, isShareMode)) {
                bRet = isFileOrDirCheckable(context, record, isShareMode);
            } else {
                bRet = true;
            }
        }
        return bRet;
    }

    private static boolean isFileOrDirCheckable(Context context, FileRecord record, boolean isShareMode) {
        if (record.isDirectory() && record.getStorageType() != StorageType.Trash) {
            return isShareMode && AppFeatures.isSupportFolderShare(context);
        } else {
            return isFileCheckable(context, record) && isFileLengthNonZero(record);
        }
    }

    private static boolean isFileCheckable(Context context, FileRecord record) {
        switch (record.getStorageType()) {
            case Local:
            case Recent:
                return isLocalOrRecentCheckable(context, record);
            case Downloads:
                return isDownloadsCheckable(context, record);
            case Trash:
                return !isSyncing(record);
            default:
                return true;
        }
    }

    private static boolean isFileLengthNonZero(FileRecord record) {
        File file = SemFwWrapper.file(record.getFullPath());
        return file.length() != 0;
    }

    private static boolean isLocalOrRecentCheckable(Context context, FileRecord record) {
        int fileType = record.getFileType();
        String fullPath = record.getFullPath();
        return !isPlayReadyOrDrm(fileType, fullPath) || DrmUtils.isForwardable(context, fullPath);
    }

    private static boolean isDownloadsCheckable(Context context, FileRecord record) {
        int fileType = record.getFileType();
        String fullPath = record.getFullPath();
        if (isPlayReadyOrDrm(fileType, fullPath)) {
            return DrmUtils.isForwardable(context, fullPath) && FileUtils.isSameAsRealFile(record);
        } else {
            return FileUtils.isSameAsRealFile(record);
        }
    }

    private static boolean isPlayReadyOrDrm(int fileType, String fullPath) {
        return FileType.isPlayReadyType(fileType) ||
                FileType.isDrmFileType(MediaFile.getFileType(fullPath, false));
    }

    private static LruCache<Long, String> sCachedSize = new LruCache<>(128);

    public static String makeFileSizeString(Context context, long fileSize) {
        String ret = sCachedSize.get(fileSize);

        if (ret == null) {
            if (context != null) {
                ret = Formatter.formatFileSize(context, fileSize);
                sCachedSize.put(fileSize, ret);
            }
        }

        return ret;
    }

    public static void clearCacheString() {
        sCachedSize.evictAll();
        clearCachedTime();
    }

    public static void clearCachedTime() {
        sCachedTime.evictAll();
    }

    public static String getContentDescription(Context context, String itemName, int type, boolean isShareableDRMFile, boolean isShareMode) {
        String itemTypeStringName = getTypeName(context, type);

        String itemDescription;

        if (type == FileType.FOLDER) {
            if (isShareMode)
                itemDescription = itemTypeStringName + ", " + itemName;
            else
                itemDescription = itemTypeStringName + ", " + itemName + ", " + context.getResources().getString(R.string.double_to_go_to_folder, itemName);
        } else if (!isShareableDRMFile) {
            if (isShareMode) {
                itemDescription = itemTypeStringName + ", " + itemName + ", " + context.getResources().getString(R.string.tts_dimmed);
            } else {
                itemDescription = itemTypeStringName + ", " + itemName;
            }
        } else
            itemDescription = itemTypeStringName + ", " + itemName + ", " + context.getResources().getString(R.string.double_tap_to_open);

        return itemDescription;
    }

    private static String getTypeName(Context context, int type) {
        String ret = "";
        int resId = -1;
        if (type == FileType.FOLDER) {
            resId = R.string.folder;
        } else if (FileType.isImageFileType(type)) {
            resId = R.string.image;
        } else if (FileType.isAudioFileType(type)) {
            resId = R.string.audio;
        } else if (FileType.isVideoFileType(type)) {
            resId = R.string.video;
        } else if (FileType.isDocumentFileType(type)) {
            resId = R.string.document;
        } else if (FileType.isApkFileType(type)) {
            resId = getInstallationFileString();
        }

        if (resId > 0) {
            ret = context.getResources().getString(resId);
        }

        return ret;
    }

    public static int getSamsungDriveString() {
        if (AppFeatures.IS_JPN) {
            return R.string.galaxy_drive;
        } else {
            return R.string.samsung_drive;
        }
    }

    public static int getInstallationFileString() {
        if (AppFeatures.isChinaModel()) {
            return R.string.category_apk;
        } else {
            return AppFeatures.isTabletUIMode() ? R.string.installation_files_tablet : R.string.installation_files;
        }
    }

    public static String getCheckableContentDescription(Context context, String itemName, int type, boolean isChecked, boolean isCheckbox) {
        String itemTypeStringName = getTypeName(context, type);

        return itemTypeStringName
                + ", "
                + itemName
                + ", "
                + ((isCheckbox) ? context.getResources().getString(R.string.tts_tick_box_t_tts) : context.getResources().getString(R.string.tts_radio_button_t_tts))
                + ", "
                + ((isChecked) ? context.getResources().getString(R.string.tts_ticked_t_tts) : context.getResources().getString(
                R.string.tts_not_ticked_t_tts));
    }

    public static String getHomeDescription(Context context, int item1, int item2) {
        return context.getResources().getString(item1) + ", " + context.getResources().getString(item2);
    }

    private static LruCache<Long, String> sCachedTime = new LruCache<>(128);

    public static String makeTimeString(Context context, long date) {
        String ret = sCachedTime.get(date);
        try {
            if (ret == null && context != null) {
                // Get date style
                String curLanguage = Locale.getDefault().getDisplayLanguage();
                String korLanguage = Locale.KOREA.getDisplayLanguage();
                int dateStyle = TextUtils.equals(curLanguage, korLanguage) ?
                        java.text.DateFormat.LONG : java.text.DateFormat.MEDIUM;

                // Get file's year is same as current year
                Calendar calendar = Calendar.getInstance();
                int curYear = calendar.get(Calendar.YEAR);
                calendar.setTimeInMillis(date);
                int fileYear = calendar.get(Calendar.YEAR);

                // Make a time string
                SimpleDateFormat dateFormat = (SimpleDateFormat) java.text.DateFormat
                        .getDateInstance(dateStyle, Locale.getDefault());
                SimpleDateFormat timeFormat = (SimpleDateFormat) DateFormat.getTimeFormat(context);

                // If the file is this year's file, Remove the year information
                if (fileYear == curYear) {
                    if (Locale.getDefault().toString().equalsIgnoreCase("pt_BR")) {
                        dateFormat.applyPattern(PATTERN_YEARLESS_DATE_FOR_PT_BR.matcher(dateFormat.toPattern()).replaceAll(""));
                    } else if (Locale.getDefault().toString().equalsIgnoreCase("lv_LV")) {
                        dateFormat.applyPattern(PATTERN_YEARLESS_DATE_FOR_LV.matcher(dateFormat.toPattern()).replaceAll("").replace(".", " "));
                    } else {
                        dateFormat.applyPattern(PATTERN_YEARLESS_DATE.matcher(dateFormat.toPattern()).replaceAll(""));
                    }
                }

                ret = dateFormat.format(date) + " \u200e" + timeFormat.format(date);
                sCachedTime.put(date, ret);
            }
        } catch (IllegalArgumentException e) {
            Log.w(TAG, "makeTimeString() ] IllegalArgumentException happened. e = " + e.getMessage());
        }

        return ret;
    }

    public static boolean isNetworkOn(Context context) {
        if (context == null) {
            return false;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
            if (netInfo != null) {
                Log.d("isNetworkOn", "netInfo.getType() = " + netInfo.getType());
                Log.d("isNetworkOn", "netInfo.getSubtype() = " + netInfo.getSubtype());
            } else {
                Log.d("isNetworkOn", "netInfo == null");
            }

            if (netInfo != null
                    && DetailedState.CONNECTED.equals(netInfo.getDetailedState())
                    && (netInfo.getType() == ConnectivityManager.TYPE_WIFI || netInfo.getType() == ConnectivityManager.TYPE_BLUETOOTH
                    || (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET)
                    || (netInfo.getType() == ConnectivityManager.TYPE_MOBILE && (netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPAP
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSUPA
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_1xRTT
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_0
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_A
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_B
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EHRPD
                    || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE)) // Add
                    // 2G
                    // type;
            )) {
                Log.w("isNetworkOn", " if (netInfo != null) netInfo.getType() = " + netInfo.getType());
                return true;
            }
        }
        return false;
    }

    // wi-fi on / off check
    public static boolean isWifiOn(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            Network networks[] = connectivityManager.getAllNetworks();
            if (networks != null && networks.length > 0) {
                for (Network network : networks) {
                    if (network != null) {
                        NetworkInfo netInfo = connectivityManager.getNetworkInfo(network);
                        if (netInfo != null && isWifiNetwork(netInfo) && DetailedState.CONNECTED.equals(netInfo.getDetailedState())) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private static boolean isWifiNetwork(NetworkInfo netInfo) {
        int type = netInfo.getType();
        boolean ret = false;
        if (type == ConnectivityManager.TYPE_WIFI
                || type == ConnectivityManager.TYPE_BLUETOOTH
                || type == ConnectivityManager.TYPE_ETHERNET) {
            ret = true;
        }
        return ret;
    }

    public static boolean isInRTLMode(Context context) {
        Configuration config;
        return !(context == null || context.getResources() == null || (config = context.getResources().getConfiguration()) == null)
                && (config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
    }

    private static long mLastClickTime = 0;
    private static final long DOUBLE_CLICK_TIME_DELTA = 400;// 1000 // milliseconds
    private static int sPrevId;

    /**
     * Prevent execute duplicated click input
     *
     * @return true/false
     */
    public static boolean isValidClick(int id) {
        return _isValidClick(id, DOUBLE_CLICK_TIME_DELTA);
    }

    public static boolean _isValidClick(int id, long delay) {
        boolean bRet = true;
        long clickTime = System.currentTimeMillis();

        if (sPrevId == id) {
            if (clickTime - mLastClickTime < delay) {
                bRet = false;
            }
        } else {
            Log.d(UiUtils.class, "isValidClick View is different");
        }

        mLastClickTime = clickTime;
        sPrevId = id;

        return bRet;
    }

    public static boolean isCloudGatewayEnabled(Context context) {
        boolean bRet = false;
        if (!AppFeatures.NO_SUPPORT_CLOUD) {
            if (CloudGatewaySignInUtils.getInstance(context).isPlatformEnabled()) {
                bRet = true;
            }
        }
        return bRet;
    }

    public static boolean canExecuteCloud(Activity activity, FragmentManager fm) {
        boolean bRet = true;
        if (!isNetworkOn(activity)) {
            bRet = false;
            UnableToAccessServerDialogFragment netDialog = UnableToAccessServerDialogFragment.getInstance(R.string.unable_to_connect_network, activity);
            netDialog.showAllowingStateLoss(fm, UnableToAccessServerDialogFragment.NETWORK_WARNING);
        } else if (!isWifiOn(activity)) {
            if (CloudGatewaySignInUtils.getInstance(activity).getWifiOnlyMode()) {
                bRet = false;
                UnableToAccessServerDialogFragment netDialog = UnableToAccessServerDialogFragment.getInstance(R.string.unable_to_connect_wifi, activity);
                netDialog.showAllowingStateLoss(fm, UnableToAccessServerDialogFragment.WIFI_WARNING);
            }
        }
        return bRet;
    }

    public static FileRecord getRecentRecord() {
        return FileRecord.createFileRecord(StorageType.Recent, AppConstants.StoragePath.RECENT_FILES);
    }

    public static FileRecord getHomeRecord(Context context, NavigationInfo curInfo) {
        StorageType storageType = StorageType.Home;
        String path = "";
        boolean isSelectOpDestination = curInfo != null && curInfo.isSelectOpDestination();
        if (!isSelectOpDestination) {
            if (AppFeatures.isTabletUIMode() ||
                    (AppFeatures.isNote() && getScreenState(context) == AppConstants.LANDSCAPE && !isInMultiWindow(getActivity(context, curInfo)))) {
                boolean showRecent = PreferenceUtils.getShowRecentFiles(context);
                if (showRecent) {
                    storageType = StorageType.Recent;
                    path = AppConstants.StoragePath.RECENT_FILES;
                } else {
                    storageType = StorageType.Local;
                    path = AppConstants.StoragePath.INTERNAL_ROOT;
                }
            }
        }
        return FileRecord.createFileRecord(storageType, path);
    }

    public static FileRecord getPrivateRootRecord(Context context, NavigationInfo navigationInfo) {
        StorageType storageType = StorageType.SecureLocal;
        String path = "";
        path = SecureConstants.privateRecoveryRootPath;
        return FileRecord.createFileRecord(storageType, path);
    }

	public static FileRecord getRootRecord(Context context, NavigationInfo curInfo) {
		StorageType storageType = StorageType.Local;
		String path = AppConstants.StoragePath.INTERNAL_ROOT;
		return FileRecord.createFileRecord(storageType, path);
	}
	
    private static Activity getActivity(Context context, NavigationInfo navigationInfo) {
        Activity ret = null;
        if (context instanceof Activity) {
            ret = (Activity) context;
        } else if (navigationInfo != null) {
            AbsMyFilesFragment fragment = navigationInfo.getCurFragment();
            if (fragment != null) {
                ret = fragment.getActivity();
            }
        }

        return ret;
    }

    public static boolean isInMultiWindow(Activity activity) {
        //TODO HYL MULTIWINDOW
        return false;
        //return (activity != null) ? activity.isInMultiWindowMode() : (getMultiWindowState() != AppConstants.MODE_NONE);
    }

    public static int getScreenState(Context context) {
        int screenState = AppConstants.PORTRAIT;
        if (context != null) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int rotation = display.getRotation();

            screenState = (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) ? AppConstants.PORTRAIT
                    : AppConstants.LANDSCAPE;

            if (display.getDisplayId() != Display.DEFAULT_DISPLAY) {
                Point point = new Point();
                display.getSize(point);
                screenState = (point.y > point.x) ? AppConstants.PORTRAIT : AppConstants.LANDSCAPE;
            }
        }
        return screenState;
    }

    public static SamsungAnalyticsLog.ScreenPath getScreenPathFromRecord(FileRecord record) {
        SamsungAnalyticsLog.ScreenPath screenPath = SamsungAnalyticsLog.ScreenPath.HOME;
        if (record.getFullPath().startsWith(AppConstants.StoragePath.INTERNAL_ROOT)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.INTERNAL_STORAGE;
        } else if (StorageMonitor.isMountedSdCardPath(record.getFullPath())) {
            screenPath = SamsungAnalyticsLog.ScreenPath.SD_CARD;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.CATEGORY_IMAGE)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.CATEGORY_IMAGE;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.CATEGORY_VIDEO)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.CATEGORY_VIDEO;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.CATEGORY_AUDIO)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.CATEGORY_AUDIO;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.CATEGORY_DOCUMENT)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.CATEGORY_DOCUMENT;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.DOWNLOADS)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.DOWNLOADS;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.CATEGORY_APK)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.INSTALLATION;
        } else if (StorageMonitor.startWithUsbRoot(record.getFullPath())) {
            screenPath = SamsungAnalyticsLog.ScreenPath.USB_STORAGE;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.SAMSUNG_DRIVE_FOLDER)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.SAMSUNG_CLOUD_DRIVE;
        } else if (record.getFullPath().startsWith(AppConstants.StoragePath.GOOGLE_DRIVE_FOLDER)) {
            screenPath = SamsungAnalyticsLog.ScreenPath.GOOGLE_CLOUD_DRIVE;
        }
        return screenPath;
    }

    public static int getSelectableItemBackground(Context context) {
        final TypedValue value = new TypedValue();
        context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, value, true);

        return value.resourceId;
    }

    public static void sendLocalBroadcastIntent(Context context, String action, int processId) {
        sendLocalBroadcastIntent(context, action, processId, null);
    }

    public static void sendLocalBroadcastIntent(Context context, String action, int processId, String tag) {
        Intent intent = new Intent(action);
        if (!TextUtils.isEmpty(tag)) {
            intent.putExtra(AppConstants.EXTRA_TAG, tag);
        }
        if (processId >= 0) {
            intent.putExtra(AppConstants.EXTRA_PROCESS_ID, processId);
        }
        if (context != null) {
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        }
    }

    public static boolean checkSamsungMembersApp(Context context) {
        boolean ret = false;

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("voc://view/contactUs"));

        intent.putExtra("packageName", context.getPackageName());
        intent.putExtra("appId", "kj1x691nkt");
        intent.putExtra("appName", "SecMyFiles");
        intent.putExtra("feedbackType", "ask");
        intent.putExtra("preloadBody", false);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            ret = true;
        }
        return ret;
    }

    public static int getInternalStorageRootResId() {
        return R.string.my_device;
    }

    public static int getHomeRecentMaxItemCnt(Activity activity, int processId) {
        int nRet = AppConstants.HOME_RECENT_MAX_ITEM_COUNT_FOUR;
        if (activity != null) {
            MultiWindowMgr.WindowState windowState = MultiWindowMgr.getInstance(activity, processId).getWindowState();
            if (windowState == MultiWindowMgr.WindowState.LANDSCAPE) {
                nRet = AppConstants.HOME_RECENT_MAX_ITEM_COUNT_EIGHT;
            }
        }
        return nRet;
    }

    public static boolean isPlayStoreInstalled(Context context) {
        if (AppFeatures.isChinaModel()) {
            return false;
        }
        boolean ret = false;
        PackageManager pm = context.getPackageManager();
        if (pm != null) {
            try {
                PackageInfo pkgInfo = pm.getPackageInfo(AppConstants.PLAY_STORE_PACKAGE_NAME, PackageManager.GET_META_DATA);
                if (pkgInfo != null) {
                    ret = true;
                }
            } catch (PackageManager.NameNotFoundException e) {
                Log.d(TAG, "play store is not exist");
            }
        }

        return ret;
    }

    public static boolean isGalaxyAppsInstalled(Context context) {
        boolean ret = false;
        PackageManager pm = context.getPackageManager();
        if (pm != null) {
            try {
                PackageInfo pkgInfo = pm.getPackageInfo(AppConstants.GALAXY_APPS_PACKAGE_NAME, PackageManager.GET_META_DATA);
                ret = (pkgInfo != null);
            } catch (PackageManager.NameNotFoundException e) {
                Log.d(TAG, "Galaxy apps is not exist");
            }
        }

        return ret;
    }

    public static int getSupportedMarketType(Context context) {
        int marketType = AppConstants.MarketType.NOT_SUPPORT;
        if (isPlayStoreInstalled(context)) {
            marketType = AppConstants.MarketType.PLAY_STORE;
        } else if (isGalaxyAppsInstalled(context)) {
            marketType = AppConstants.MarketType.GALAXY_APPS;
        }
        return marketType;
    }

    public static void limitLargeTextSize(Context context, TextView tv) {
        if (tv != null) {
            float MAX_FONT_SCALE = AppConstants.SELECTED_COUNT_ITEM_MAX_FONT_SCALE;
            float currentTextSize = tv.getTextSize();
            float fontScale = context.getResources().getConfiguration().fontScale;
            float defaultTextSize = currentTextSize / fontScale;
            if (fontScale > MAX_FONT_SCALE) {
                fontScale = MAX_FONT_SCALE;
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize * fontScale);
            }

        }
    }

    public static void setBtnBackgroundColor(Context context, TextView v) {
        if (v != null) {
            if (AppFeatures.isEnableButtonBackgrounds(context)) {
                if (v.isEnabled()) {
                    v.setBackgroundResource(R.drawable.action_bar_btn_background);
                }
            }
        }
    }

    public static void toggleListType(int processId, Context context, FileRecord curRecord) {
        PreferenceUtils.ViewAsKey viewAsKey = PreferenceUtils.getViewAsKey(curRecord);
        int viewType = PreferenceUtils.getViewAs(context, viewAsKey);
        int toViewType;

        if ((viewType == AppConstants.ViewType.LIST) || (viewType == AppConstants.ViewType.LIST_DETAIL)) {
            toViewType = AppConstants.ViewType.GRID;
            SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.VIEW_AS_GRID, null);
        } else {
            toViewType = AppConstants.ViewType.LIST_DETAIL;
            SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.VIEW_AS_LIST, null);
        }

        PreferenceUtils.setViewAs(context, toViewType, viewAsKey);
        refreshLocalBroadcastIntent(context, AppConstants.MYFILES_ACTION_VIEW_AS_CHANGED);
    }

    public static void refreshLocalBroadcastIntent(Context context, String action) {
        ArrayList<Integer> processList = NavigationManager.getProcessIdList();

        for (int processId : processList) {
            if (isActionSupported(action, processId)) {
                NavigationInfo curInfo = NavigationManager.getInstance(processId).getCurInfo();
                if (curInfo != null) {
                    AbsMyFilesFragment fragment = curInfo.getCurFragment();
                    if (fragment != null && fragment.isSelectActionMode()) {
                        fragment.setNeedRefreshViewAs(true);
                    } else {
                        NavigationManager.getInstance(processId).refreshNotify();
                    }
                }
            }
            sendLocalBroadcastIntent(context, action, processId);
        }
    }

    private static boolean isActionSupported(String action, int processId) {
        boolean ret = true;
        NavigationInfo curInfo = NavigationManager.getInstance(processId).getCurInfo();
        if (curInfo != null) {
            StorageType storageType = curInfo.getStorageType();
            if (AppConstants.MYFILES_ACTION_VIEW_AS_CHANGED.equals(action)) {
                if (storageType == StorageType.Home || storageType == StorageType.Search || storageType == StorageType.OptimizeStorage) {
                    ret = false;
                }
            }
        }
        return ret;
    }

    public static boolean isShareAvailable(Context context, FileRecord record) {
        boolean ret = false;
        if (!record.isDirectory() || AppFeatures.isSupportFolderShare(context)) {
            ret = true;
        }
        return ret;
    }

    public static String makeDurationString(long time) {
        long duration = time / 1000;
        long hours = duration / 3600;
        long minutes = (duration - hours * 3600) / 60;
        long seconds = duration - (hours * 3600 + minutes * 60);

        return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
    }


    private static FileRecord.CategoryType getCategoryType(ArrayList<FileRecord> selectedFile) {
        FileRecord.CategoryType ret = FileRecord.CategoryType.None;
        Log.d(TAG, "getCategoryType: set none as default");

        for (int i = 0; i < selectedFile.size(); i++) {
            FileRecord record = selectedFile.get(i);
            FileRecord.CategoryType curType = FileRecord.CategoryType.None;
            if (record != null) {
                if (record.isDirectory())
                    curType = FileRecord.CategoryType.Folder;
                else if (record.isImageFileType())
                    curType = FileRecord.CategoryType.Image;
                else if (record.isAudioFileType())
                    curType = FileRecord.CategoryType.Audio;
                else if (record.isVideoFileType())
                    curType = FileRecord.CategoryType.Video;
                else if (record.isDocumentFileType())
                    curType = FileRecord.CategoryType.Document;
                else if (record.isApkFileType())
                    curType = FileRecord.CategoryType.Apk;

                if (ret != FileRecord.CategoryType.None) {
                    if (curType != ret) {
                        ret = FileRecord.CategoryType.None;
                        Log.d(TAG, "getCategoryType: is not one category");
                        break;
                    }
                } else if (i == 0) {
                    ret = curType;
                    Log.d(TAG, "getCategoryType: is first item or is not categorized item");
                }
            }
        }
        return ret;
    }

    public static String makeSelectedItemsString(Context context, ArrayList<FileRecord> selectedFile) {
        int resId = R.plurals.n_items_selected;
        int size = selectedFile.size();

        FileRecord.CategoryType type = getCategoryType(selectedFile);

        switch (type) {
            case Folder:
                resId = R.plurals.n_folders_selected;
                break;
            case Image:
                resId = R.plurals.n_image_files_selected;
                break;
            case Audio:
                resId = R.plurals.n_audio_files_selected;
                break;
            case Video:
                resId = R.plurals.n_video_files_selected;
                break;
            case Document:
                resId = R.plurals.n_document_files_selected;
                break;
            case Apk:
                resId = R.plurals.n_apk_files_selected;
                break;
            case None:
            default:
                break;
        }
        return context.getResources().getQuantityString(resId, size, size);
    }

    public static String makeCopiedItemsString(Context context, ArrayList<FileRecord> selectedFile) {
        int resId = R.plurals.n_items_copied;
        int size = selectedFile.size();

        int itemType = FileUtils.getRecordType(selectedFile);

        switch (itemType) {
            case FileUtils.ITEM_TYPE.FOLDER:
                resId = R.plurals.n_folders_copied;
                break;
            case FileUtils.ITEM_TYPE.FILE:
                resId = R.plurals.n_files_copied;
                break;
            default:
                break;
        }
        return context.getResources().getQuantityString(resId, size, size);
    }

    public static String makeMovedItemsString(Context context, ArrayList<FileRecord> selectedFile) {
        int resId = R.plurals.n_items_cut;
        int size = selectedFile.size();

        int itemType = FileUtils.getRecordType(selectedFile);

        switch (itemType) {
            case FileUtils.ITEM_TYPE.FOLDER:
                resId = R.plurals.n_folders_cut;
                break;
            case FileUtils.ITEM_TYPE.FILE:
                resId = R.plurals.n_files_cut;
                break;
            default:
                break;
        }
        return context.getResources().getQuantityString(resId, size, size);
    }

    public static String makeContainsString(Context context, int fileCount, int folderCount) {
        StringBuilder sb = new StringBuilder();
        if (fileCount != 0) {
            if (fileCount != 1) {
                sb.append(context.getResources().getString(R.string.n_files_n_files, fileCount));
            } else {
                sb.append(context.getResources().getString(R.string.n_files_1_file));
            }
        }
        if (folderCount != 0) {
            if (sb.length() != 0) {
                sb.append(context.getResources().getString(R.string.comma)).append(" ");
            }
            if (folderCount != 1) {
                sb.append(context.getResources().getString(R.string.n_folders_n_folders, folderCount));
            } else {
                sb.append(context.getResources().getString(R.string.n_folders_1_folder));
            }
        }
        if (fileCount == 0 && folderCount == 0) {
            sb.append(context.getResources().getQuantityString(R.plurals.n_items, fileCount, fileCount));
        }
        return sb.toString();
    }

    public static String makeItemsString(Context context, int size) {
        return context.getResources().getQuantityString(R.plurals.n_items, size, size);
    }

    public static String makeSelectedString(Context context, int count) {
        return context.getResources().getString(R.string.n_selected, count);
    }

    public static void setHomeItemIcon(Context context, FileRecord record, ImageView homeIconView) {
        String path = record.getFullPath();
        int resIconId = -1;
        int resIconColorId = -1;
        if (record.getStorageType() == StorageType.Recent) {
            resIconId = R.drawable.my_files_ic_recent_files;
            resIconColorId = R.color.home_icon_recent_color;
        } else if (record.getStorageType() == StorageType.Downloads) {
            resIconId = R.drawable.my_files_ic_download_history;
            resIconColorId = R.color.home_icon_download_history_color;
        } else if (record.getStorageType() == StorageType.FolderTree || record.getStorageType() == StorageType.Local) {
            if (path.equalsIgnoreCase(AppConstants.StoragePath.INTERNAL_ROOT)) {
                resIconId = R.drawable.my_files_ic_phonestorage;
                resIconColorId = R.color.home_icon_device_storage_color;
            } else if (path.equalsIgnoreCase(StorageMonitor.getExtSDCardPath())) {
                resIconId = R.drawable.my_files_ic_storage;
                resIconColorId = R.color.home_icon_sd_card_color;
            } else if (path.equalsIgnoreCase(PrivateModeMgr.getInstance(context).getRootDir())) {
                resIconId = R.drawable.my_files_ic_personalpage;
                resIconColorId = R.color.home_icon_device_storage_color;
            } else if (StorageMonitor.startWithUsbRoot(path)) {
                for (int i = StorageMonitor.iStorageType.EXTERNAL_USB_DRIVE_A; i <= StorageMonitor.iStorageType.EXTERNAL_USB_DRIVE_F; i++) {
                    String usbPath = StorageMonitor.getUsbStoragePath(i);
                    if (usbPath != null && path.equalsIgnoreCase(usbPath)) {
                        resIconId = R.drawable.my_files_ic_usb;
                        resIconColorId = R.color.home_icon_usb_storage_color;
                        break;
                    }
                }
            } else {
                resIconId = R.drawable.myfiles_ic_folder;
                resIconColorId = R.color.home_icon_folder;
            }
        } else if (record.getStorageType() == StorageType.Category) {
            FileRecord.CategoryType type = CategoryFileRecord.getCategoryType(record.getFullPath());
            switch (type) {
                case Image:
                    resIconId = R.drawable.my_files_ic_image;
                    resIconColorId = R.color.home_icon_image_color;
                    break;
                case Audio:
                    resIconId = R.drawable.my_files_ic_music;
                    resIconColorId = R.color.home_icon_music_color;
                    break;
                case Video:
                    resIconId = R.drawable.my_files_ic_video;
                    resIconColorId = R.color.home_icon_video_color;
                    break;
                case Document:
                    resIconId = R.drawable.my_files_ic_document;
                    resIconColorId = R.color.home_icon_document_color;
                    break;
                case Apk:
                    resIconId = R.drawable.my_files_ic_apk;
                    resIconColorId = R.color.home_icon_apk_color;
                    break;
            }
        } else if (record.getStorageType() == StorageType.Cloud) {
            if (record.getFullPath().startsWith(AppConstants.StoragePath.GOOGLE_DRIVE_FOLDER)) {
                resIconId = R.drawable.my_files_ic_drive;
                resIconColorId = R.color.home_icon_google_drive_color;
            } else if (record.getFullPath().startsWith(AppConstants.StoragePath.SAMSUNG_DRIVE_FOLDER)) {
                resIconId = R.drawable.my_files_ic_cloud;
                resIconColorId = R.color.home_icon_samsung_drive_color;
            }
        } else if (record.getStorageType() == StorageType.Shortcut) {
            resIconId = R.drawable.my_files_ic_folder_shortcut;
            resIconColorId = R.color.home_icon_folder;
        }

        if (resIconId < 0 && resIconColorId < 0) {
            resIconId = R.drawable.myfiles_ic_folder;
            resIconColorId = R.color.home_icon_folder;
        }
        homeIconView.setImageResource(resIconId);
        homeIconView.setColorFilter(ContextCompat.getColor(context, resIconColorId));
    }

    public static void setWindowAttribute(Activity activity, AbsLayoutImp layoutImp) {
        Window window = activity.getWindow();
        Context context = activity.getApplicationContext();

        if (window != null) {
            if (getScreenState(context) == AppConstants.LANDSCAPE) {
                if (layoutImp instanceof TabletLayoutImp) {
                    window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                } else {
                    window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                    window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                }
            } else {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            }
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            WindowManager.LayoutParams lp = window.getAttributes();
            SecApiWrapper.getActivityLayoutParam(lp);
            window.setAttributes(lp);
        }
    }

    public static boolean supportOptimizeStorage(Context context) {
        return !AppFeatures.isKnox() &&
                !isUPSM(context) &&
                !AppFeatures.isAndroidForWork() &&
                !OptimizeStorageFileRecord.isWorking();
    }

    public static boolean supportCloudGateway(Context context) {
        return !AppFeatures.isKnox() &&
                !isUPSM(context) &&
                isCloudGatewayEnabled(context) &&
                !AppFeatures.isAndroidForWork();
    }

    public static void replaceFragment(Fragment fragment) {
        FragmentTransaction ft = fragment.getFragmentManager().beginTransaction();
        ft.detach(fragment).attach(fragment).commitAllowingStateLoss();
    }

    public static boolean isDensityDpiChanged(Configuration config, int density) {
        return config.densityDpi != density;
    }

    public static boolean isSyncing(FileRecord record) {
        if (record != null) {
            if (record instanceof TrashFileRecord) {
                TrashFileRecord trashRecord = (TrashFileRecord) record;
                if (trashRecord.isDirectory()
                        && TextUtils.equals(trashRecord.getTrashProcessing(), CloudGatewayMediaStore.Trash.TRASH_ONGOING_STATUS)) {
                    return true;
                }
            } else if (record instanceof CloudFileRecord) {
                CloudFileRecord cloudRecord = (CloudFileRecord) record;
                if (cloudRecord.isDirectory()
                        && TextUtils.equals(cloudRecord.getTrashProcessing(), CloudGatewayMediaStore.Trash.RESTORE_ONGOING_STATUS)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String makeResolutionString(Context context, int[] resolutionInfo) {
        String resolution = null;
        int width = resolutionInfo[0];
        int height = resolutionInfo[1];
        if (width > 0 && height > 0) {
            if (isInRTLMode(context)) {
                resolution = String.format(Locale.getDefault(), "%dx%d", height, width);
            } else {
                resolution = String.format(Locale.getDefault(), "%dx%d", width, height);
            }
        }
        return resolution;
    }

    public static void setOnHoverListener(final Context context, View v) {
    }

    public static void setMousePointerIcon(Context context, View v, boolean isPressed) {
    }

    public static void setMousePointerIcon(Context context, int type) {
    }

    public static void setMousePointerIconToDefault() {
    }

    private static int sMaxPinchDepth = 2;

    public static int getMaxPinchDepth() {
        return sMaxPinchDepth;
    }

    public static void setMaxPinchDepth(int maxPinchDepth) {
        sMaxPinchDepth = maxPinchDepth;
    }

    public static boolean isCategoryFolderList(FileRecord record) {
        boolean bRet = false;
        if (record instanceof CategoryFileRecord) {
            if (((CategoryFileRecord) record).getBucketId() == null) {
                bRet = true;
            }
        }
        return bRet;
    }

    public static boolean isCategoryFolderList(Context context) {
        boolean bRet = false;
        NavigationInfo navigationInfo = NavigationManager.getInstance(((AbsMyFilesActivity) context).getProcessId()).getCurInfo();
        if (navigationInfo != null) {
            FileRecord record = navigationInfo.getCurRecord();
            if (record != null && isCategoryFolderList(record)) {
                bRet = true;
            }
        }
        return bRet;
    }

    public static String getDrmWarningMessage(Context context, FileOperator.Operation op, int countDrm) {
        String result = null;
        int resId = -1;
        switch (op) {
            case COPY:
                resId = R.plurals.n_item_drm_not_copy_to_samsung_cloud;
                break;
            case MOVE:
                resId = R.plurals.n_item_drm_not_move_to_samsung_cloud;
                break;
            default:
                break;
        }

        if (resId != -1 && countDrm > 0) {
            result = context.getResources().getQuantityString(resId, countDrm);
        }

        return result;
    }

    public static void setContentsArea(Activity activity, int contentsViewResId, int screenWidthDp) {
        if (AppFeatures.isTabletUIMode()) {
            boolean makePartialArea = screenWidthDp > AppConstants.SCREEN_WIDTH_DP_800 &&
                    (AppFeatures.isKnoxDesktopMode() || (AppFeatures.isTablet() && getScreenState(activity) == AppConstants.LANDSCAPE));
            setContentsArea(activity, contentsViewResId, makePartialArea);
        }
    }

    public static void setContentsArea(Activity activity, int contentsViewResId, boolean makePartialArea) {
        float weight;
        if (AppFeatures.isTabletUIMode()) {
            View contentsView = activity.findViewById(contentsViewResId);
            if (contentsView != null && contentsView.getParent() instanceof LinearLayout) {
                if (makePartialArea) {
                    weight = PARTIAL_VIEW_WEIGHT;
                    contentsView.setForeground(activity.getDrawable(R.drawable.partial_contents_view_background));
                } else {
                    weight = FULL_VIEW_WEIGHT;
                    contentsView.setForeground(null);
                }
                contentsView.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, weight));
            }
        }
    }

    public static void setToggleMenuItem(Context context, FileListActionMenu actionMenu, NavigationInfo navigationInfo, boolean enabled) {
        if (actionMenu != null) {
            Menu menu = actionMenu.getMenuInstance();
            if (menu != null) {
                MenuItem menuItem = menu.findItem(R.id.menu_toggle_list_type);
                if (menuItem != null && navigationInfo != null) {
                    FileRecord curRecord = navigationInfo.getCurRecord();
                    if (curRecord != null) {
                        PreferenceUtils.ViewAsKey viewAsKey = PreferenceUtils.getViewAsKey(curRecord);
                        int viewType = PreferenceUtils.getViewAs(context, viewAsKey);
                        if (viewType == AppConstants.ViewType.LIST || viewType == AppConstants.ViewType.LIST_DETAIL || curRecord instanceof SearchFileRecord) {
                            menuItem.setIcon(context.getResources().getDrawable(R.drawable.action_bar_toggle_menu_grid_icon, context.getTheme()));
                            menuItem.setTitle(context.getResources().getString(R.string.grid));
                        } else {
                            menuItem.setIcon(context.getResources().getDrawable(R.drawable.action_bar_toggle_menu_list_icon, context.getTheme()));
                            menuItem.setTitle(context.getResources().getString(R.string.list));
                        }
                        menuItem.setEnabled(enabled);
                    }
                }
            }
        }
    }

    public static void showCloudUsage(Context context, AbsMyFilesFragment fragment, FileRecord record) {
        if (fragment != null && !fragment.getLoadingStatus() && fragment.isAdded()) {
            if (fragment.getNavigationInfo() != null) {
                SamsungAnalyticsLog.sendLog(fragment.getProcessId(), SamsungAnalyticsLog.Event.CLOUD_USAGE, null);
            }
            if (record != null && record.getFullPath().startsWith(AppConstants.StoragePath.SAMSUNG_DRIVE_FOLDER)) {
                if (isSamsungCloudEnable(context)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setClassName("com.samsung.android.scloud", "com.samsung.android.scloud.app.ui.SCloudActivity");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("baseFragment", "cloud_usage_status");
                    fragment.startActivity(intent);
                }
            } else {
                Intent intent = new Intent(context, CloudUsageActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                fragment.startActivity(intent);
            }
        }
    }

    public static boolean isSamsungCloudEnable(Context context) {
        boolean bRet = false;

        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo("com.samsung.android.scloud", 0);
            if (ai != null && ai.enabled) {
                bRet = true;
            }
        } catch (Exception var4) {
            android.util.Log.d(TAG, "Scloud not enable : " + var4.getMessage());
        }

        return bRet;
    }

    public static long[] updateQuota(Context context, CloudMgr cloudMgr, FileRecord.CloudType cloudType) {
        long[] quota = null;
        Bundle resultBundle = CloudGatewayDeviceInfoUtils.getInstance(context).getVersatileInformation(CloudGatewayDeviceInfoUtils.UPDATE_QUOTA, cloudMgr.getDeviceId(cloudType));
        if (resultBundle != null) {
            quota = resultBundle.getLongArray("result");
            if (quota != null && quota.length != 0) {
                CloudMgr.getInstance(context).setSize(cloudType, quota[0], quota[1]);
            }
        }
        return quota;
    }

    public static boolean isShowRecentFilesOff(Context context, FileRecord curRecord) {
        boolean bRet = false;
        boolean bSearchRecentOpened = false;
        if (curRecord != null) {
            if (curRecord instanceof SearchFileRecord) {
                FileRecord preRecord = ((SearchFileRecord) curRecord).getPreRecord();
                bSearchRecentOpened = preRecord != null && preRecord instanceof RecentFileRecord;
            }
            if ((curRecord.getStorageType() == StorageType.Recent || bSearchRecentOpened) && !PreferenceUtils.getShowRecentFiles(context)) {
                bRet = true;
            }
        }
        return bRet;
    }

    public static boolean isFullScreen(Activity activity) {
        boolean bRet = false;
        int flags = activity.getWindow().getAttributes().flags;
        if ((flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) {
            bRet = true;
        }
        return bRet;
    }

    public static boolean isArabic(String str) {
        int len = str.length();
        for (int i = 0; i < len; ) {
            int c = str.codePointAt(i);
            if (c >= 0x0600 && c <= 0x06E0) {
                return true;
            }
            i += Character.charCount(c);
        }
        return false;
    }

    public static int getMultiWindowState() {
        return 0;   //TODO HYL MULTI WINDOW
    }

    public static boolean isSectionDivider(FileRecord record) {
        boolean bRet = false;
        if (record == null || (record.getPath() == null && record.getName() == null)) {
            bRet = true;
        }
        return bRet;
    }

    public static boolean checkUnder3GBRam(Context context) {
        boolean bRet = false;
        ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
        actManager.getMemoryInfo(memInfo);

        long total = memInfo.totalMem;
        total = total / (1024 * 1024);
        long totalROM = StorageMonitor.getInternalTotalSize(context);
        totalROM = totalROM / (1024 * 1024);

        if ((total <= 3072) && (totalROM <= 32768)) {
            bRet = true;
        }
        return bRet;
    }

    public static void showToast(Context context, int strId) {
        Toast.makeText(new ContextThemeWrapper(context.getApplicationContext(), android.R.style.Theme_DeviceDefault_Light),
                strId, Toast.LENGTH_LONG).show();
    }

    public static boolean supportRecentTitle(Context context) {
        boolean bRet = false;
        if (AppFeatures.supportRecentTitleModel() || UiUtils.checkUnder3GBRam(context)) {
            bRet = true;
        }
        return bRet;
    }

    public static String getQuantityString(Resources res, int plural_id, int quantity, Object... formatArgs) {
        quantity = (quantity != 1) ? PLURAL_QUANTITY_OTHER : quantity;
        return res.getQuantityString(plural_id, quantity, formatArgs);
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        int count = listAdapter.getCount();

        for (int i = 0; i < count; i++) {
            view = listAdapter.getView(i, view, listView);
            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (count - 1));
        listView.setLayoutParams(params);
    }

    public static boolean isLandscapeMode(Context context) {
        return UiUtils.getScreenState(context) == AppConstants.LANDSCAPE || AppFeatures.isTabletUIMode();
    }
}